<!-- 业务配置 -->
<template>
	<div>
		<!-- 搜索表单 -->
		<el-form :model="searchFormData" :inline="true">
			<el-row :gutter="10">
				<el-col :span="6">
					<el-form-item label="系统名称：">
						<el-select v-model="searchFormData.systemId" placeholder="请选择系统名称">
							<el-option v-for="item in state.systemOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="业务名称：" prop="name">
						<el-input v-model="searchFormData.name" placeholder="请输入业务名称" clearable class="yd-input" />
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="标识属性：">
						<custom-select ref="customSelectRef" :config="{ placeholder: '请设置标识属性', val: '其他筛选' }">
							<div>
								<el-table
									ref="effectAttrTable"
									size="small"
									height="270px"
									style="width: 1000px"
									:data="effectAttrTableData"
									@selection-change="selectionEffectAttr"
								>
									<el-table-column align="center" type="selection" min-width="5%"></el-table-column>
									<el-table-column align="left" prop="attrName" label="筛选条件" min-width="35%"></el-table-column>
									<el-table-column align="left" prop="" label="条件值" min-width="55%">
										<template #default="scope">
											<div v-if="scope.row.field != 'relevance' && scope.row.field != 'decode'">
												<el-radio v-model="scope.row.val" :label="1">是</el-radio>
												<el-radio v-model="scope.row.val" :label="0">否</el-radio>
											</div>
											<div v-else-if="scope.row.field == 'relevance'" v-for="(option, index) in options.relevanceEffectOptions" :key="index">
												<el-radio v-model="scope.row.re" :label="option.value"> {{ option.label }} </el-radio>
											</div>
											<div v-else-if="scope.row.field == 'decode'" v-for="(option, index) in options.decodeEffectOptions" :key="index + 1">
												<el-radio v-model="scope.row.dec" :label="option.value"> {{ option.label }} </el-radio>
											</div>
										</template>
									</el-table-column>
								</el-table>
								<hr />
								<div style="text-align: center">
									<el-button size="small" @click="$refs.customSelectRef.hideCustom()">关闭</el-button>
								</div>
							</div>
						</custom-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item>
						<el-button type="primary" icon="Search" @click="handlerQuery">查 询</el-button>
					</el-form-item>
				</el-col>
			</el-row>

			<!-- <el-form-item label="步骤设置" prop="stepSet">
				<el-select v-model="searchFormData.stepSet" placeholder="请选择步骤设置" clearable>
					<el-option v-for="item in options.stepSetOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item> -->

			<div style="z-index: 1">
				<div class="effect-attr-selects" v-for="(option1, index) in currentEffectSelects" :key="index">
					<div v-if="option1.field != 'relevance' && option1.field != 'decode'">
						<div>
							<div style="float: left; line-height: 34px">{{ option1.attrName }}：</div>
							<div style="float: left">
								<el-radio v-model="option1.val" :label="1">是</el-radio>
								<el-radio v-model="option1.val" :label="0">否</el-radio>
							</div>
						</div>
					</div>
					<div v-else-if="option1.field == 'relevance'">
						<div style="float: left; line-height: 34px">{{ option1.attrName }}：</div>
						<div v-for="(option, index) in options.relevanceEffectOptions" :key="index" style="float: left">
							<el-radio v-model="option1.re" :label="option.value"> {{ option.label }} </el-radio>
						</div>
					</div>
					<div v-else-if="option1.field == 'decode'">
						<div style="float: left; line-height: 34px">{{ option1.attrName }}：</div>
						<div v-for="(option, index) in options.decodeEffectOptions" :key="index + 1" style="float: left">
							<el-radio v-model="option1.dec" :label="option.value"> {{ option.label }} </el-radio>
						</div>
					</div>
				</div>
			</div>
		</el-form>

		<!-- 数据列表 -->
		<YdTable
			:formData="searchFormData"
			:tableConfig="tableConfig"
			:tableData="tableData.data"
			@sizeChangeHandler="handlerQuery"
			@currentChangeHandler="handlerQuery"
			@sortChangeHandler="handlerQuery"
			@selectionChangeHandler="handlerSelectionChange"
		>
		</YdTable>

		<!-- 添加或修改参数配置对话框 -->
		<el-dialog :title="dialog.addOrUpdate.title" v-model="dialog.addOrUpdate.open" width="600px" append-to-body center>
			<el-form ref="addOrUpdateForm" :model="dialog.addOrUpdate.form" :rules="dialog.addOrUpdate.rule" label-width="120px">
				<el-form-item label="业务名称" prop="name">
					<el-input v-model="dialog.addOrUpdate.form.name" placeholder="请输入业务名称" maxlength="200"></el-input>
				</el-form-item>
				<!-- <el-form-item label="步骤类型" prop="type">
					<el-select v-model="dialog.addOrUpdate.form.type" placeholder="请选择步骤类型" style="width: 100%">
						<el-option v-for="(option, index) in options.stepTypeOptions" :key="index" :label="option.label" :value="option.value"> </el-option>
					</el-select>
				</el-form-item> -->
				<el-form-item label="是否关键业务" prop="isKey">
					<el-select v-model="dialog.addOrUpdate.form.isKey" @change="changeKeyBusiness" placeholder="请选择是否关键业务" style="width: 100%">
						<el-option v-for="(option, index) in options.keyOptions" :key="index" :label="option.label" :value="option.value"> </el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="业务展示顺序" prop="sequence">
					<el-input-number
						v-model="dialog.addOrUpdate.form.sequence"
						placeholder="请输入业务展示顺序"
						:disabled="addDialogForm.showOrderDisabled"
						:controls="false"
						:max="1000000"
						style="width: 100%"
					></el-input-number>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button type="primary" @click="handlerSubmit" :loading="dialog.addOrUpdate.btnLoading">确 定</el-button>
				<el-button @click="closeAddOrUpdateDialog">取 消</el-button>
			</template>
		</el-dialog>

		<!-- 专属指标导入/导出弹出层 -->
		<el-dialog
			:key="importIndicatorDialogKey"
			:title="dialog.imp.title"
			v-model="dialog.imp.open"
			width="1000px"
			:close-on-click-modal="false"
			center
			@closed="importIndicatorDialogKey -= 1"
		>
			<el-form :model="impSearchFormData" :inline="true" :label-width="100">
				<el-form-item label="业务名称" prop="name">
					<el-input v-model="impSearchFormData.name" placeholder="请输入业务名称" clearable class="yd-input" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" icon="Search" @click="handlerImpQuery">查 询</el-button>
				</el-form-item>
			</el-form>
			<!-- 数据列表 -->
			<el-row :gutter="10">
				<el-col :span="24">
					<el-table :data="impTableData.data" row-key="id" ref="myTableRef" :tree-props="{ children: 'stepList' }" @select-all="selectAllChange">
						<!-- 自定义复选框 -->
						<el-table-column type="selection">
							<template #default="{ row }">
								<el-checkbox :indeterminate="row.isIndeterminate" v-model="row.checked" @change="handleCheck(row)"></el-checkbox>
							</template>
						</el-table-column>
						<el-table-column prop="name" label="业务名称"></el-table-column>
						<!-- 其他列 -->
					</el-table>
					<el-pagination
						v-show="impTableConfig.pagination.total > 0"
						class="yd-pagination"
						layout="total, sizes, prev, pager, next, jumper"
						v-model:current-page="impSearchFormData.pageNum"
						v-model:page-size="impSearchFormData.pageSize"
						:page-sizes="[10, 20, 30, 50, 100]"
						:total="impTableConfig.pagination.total"
						@size-change="handlerImpQuery"
						@current-change="handlerImpQuery"
					>
					</el-pagination>
				</el-col>
			</el-row>
			<br />

			<div style="text-align: center">
				<el-upload
					action="#"
					:limit="1"
					:accept="'xlsx,xls'"
					:on-success="handlerSuccess"
					:on-change="fileChange"
					:on-remove="handlerRemove"
					:on-error="handlerError"
					:file-list="fileList"
					:auto-upload="false"
				>
					<el-button size="small" type="primary" v-if="dialog.imp.title === '导入'">上 传</el-button>
				</el-upload>
			</div>
			<template #footer>
				<el-button type="primary" @click="downloadTemplate" v-if="importFlag">下载模板</el-button>
				<el-button type="primary" @click="handlerImport" v-if="importFlag">确 定</el-button>
				<el-button type="primary" @click="handlerExport" v-if="!importFlag">下 载</el-button>
				<el-button @click="closeImpDialog">取 消</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="BusinessConfig" lang="tsx">
import CustomSelect from '@/components/CustomSelect/index.vue';
import { synchronousBusinessOptions } from '@/utils/admin/options';
import {
	querySynchronousBusiness,
	addSynchronousBusiness,
	editSynchronousBusiness,
	deleteSynchronousBusinessByIds,
	confirmByIds,
	cancelByIds,
	importTemplate,
	queryToImport,
	download,
	batchImport,
} from '@/api/admin/businessMonitor/businessConfig';
import { query, step } from '@/api/admin/businessMonitor/businessStepConfig';
import { getToken } from '@/utils/auth';
import { downloadFromBlob } from '@/utils/common';
import { getCurrentInstance, nextTick, onActivated, onBeforeMount, onMounted, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { system } from '@/api/admin/businessMonitor/businessStepConfig';

const { proxy }: any = getCurrentInstance();
const route = useRoute();
const fileList = ref([] as any);
const effectAttrTableData = ref([
	{
		field: 'isConfirm',
		attrName: '确认状态',
		val: 1,
		re: '0',
		dec: 'no',
	},
	{
		field: 'isKey',
		attrName: '是否关键业务',
		val: 1,
		re: '0',
		dec: 'no',
	},
]);
const currentEffectSelects = ref([]);
const importFlag = ref(true);
// 导入导出选择的行数据ids
const selectedImpIds = ref([]);
// 导入导出选择的行数据
const selectedImp = ref({});
// 导入导出选择的行数据ids
const selectedImpStepCodes = ref([]);
// 导入导出选择的行数据
const selectedImpStep = ref({});
// 专属指标导入弹出层key
const importIndicatorDialogKey = ref(-1);
//枚举变量
const options: any = ref(synchronousBusinessOptions());
// 搜索表单数据
let searchFormData = reactive<any>({
	pageSize: 10,
	pageNum: 1,
	// 默认按启动时间降序
	orderByColumn: 'sequence',
	isAsc: 'desc',
	type: '',
	...route.query,
});
// 新增显示层
let addDialogForm = reactive({
	showOrderDisabled: true,
});
// 列表配置
let tableConfig = reactive({
	// remote: querySynchronousBusiness,
	columns: [
		{
			label: '业务名称',
			prop: 'name',
			render: (row: any, val: any) => {
				// if (proxy.checkRole(['admin']) || proxy.checkPermi(['synchronousBusiness:processList'])) {
				const router = {
					path: '/management/stepManage/businessStepConfig',
					query: {
						systemId: row.systemId,
						businessCode: row.businessCode,
					},
				};
				return (
					<router-link to={router} class="link-type" style={{ color: '#2beded' }}>
						<span>{val}</span>
					</router-link>
				);
				// }
				return <span>{val}</span>;
			},
		},
		{
			label: '业务编码',
			prop: 'businessCode',
			showOverFlowToolTip: true,
		},
		{
			label: '确认状态',
			prop: 'isConfirm',
			formatter: (row: any, val: any) => {
				return options.value.statusOptionsMap[val];
			},
		},
		{
			label: '确认时间',
			prop: 'updateTime',
		},
		{
			label: '关键业务',
			prop: 'isKey',
			formatter: (row: any, val: any) => {
				return options.value.keyOptionsMap[val];
			},
		},
		{
			label: '显示顺序',
			prop: 'sequence',
			showOverFlowToolTip: true,
			sortable: true,
		},
	],
	// 工具栏
	toolBar: [
		{ name: '新增', icon: 'yd-icon-plus', permi: ['synchronousBusiness:add'], handler: () => handlerAdd() },
		{
			name: '修改',
			icon: 'yd-icon-edit',
			permi: ['synchronousBusiness:update'],
			disable: 'single',
			handler: () => handlerEdit(),
		},
		{
			name: '删除',
			icon: 'yd-icon-delete',
			permi: ['synchronousBusiness:delete'],
			disable: 'multiple',
			handler: () => handlerDelete(),
		},
		{
			name: '确认',
			icon: 'yd-icon-confirm',
			permi: ['synchronousBusiness:confirm'],
			disable: 'check',
			handler: () => handlerConfirm(),
			check: () => checkStatus(0),
		},
		{
			name: '取消',
			icon: 'yd-icon-cancel',
			permi: ['synchronousBusiness:cancel'],
			disable: 'check',
			handler: () => handlerCancel(),
			check: () => checkStatus(1),
		},
		{
			name: '导入专属指标',
			icon: 'yd-icon-import',
			permi: ['indicator:detail:import'],
			handler: () => handlerImport(),
		},
		{
			name: '导出专属指标',
			icon: 'yd-icon-export',
			permi: ['indicator:detail:export'],
			handler: () => handlerExport(),
		},
	],
	// 开启复选框
	enableSelection: true,
	// 开启分页
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 加载层
	loading: true,
});
// 列表数据
let tableData = reactive<any>({
	data: [],
	total: 0,
});
let impSearchFormData = reactive<any>({
	pageSize: 10,
	pageNum: 1,
	// 默认按启动时间降序
	orderByColumn: 'sequence',
	isAsc: 'desc',
});
let impTableConfig = reactive<any>({
	columns: [
		{
			label: '业务名称',
			prop: 'name',
		},
	],
	// 开启复选框
	enableSelection: true,
	// 开启单击事件
	rowClick: true,
	expand: true,
	// 开启分页
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 加载层
	loading: true,
	radioRow: {},
});
// 列表数据
let impTableData = reactive<any>({
	data: [],
	total: 0,
});
const impTableFormData = reactive<any>({
	name: '',
});
// 列表数据
let impStepTableData = reactive<any>({
	data: [
		{
			businessCode: 1,
			name: '123123123',
			stepList: [
				{ businessCode: 11, name: '123' },
				{ businessCode: 12, name: '12' },
				{ businessCode: 13, name: '11323' },
				{ businessCode: 14, name: '113423' },
			],
		},
	],
	total: 0,
});
// 勾选记录
let record = reactive<any>({
	business: {},
	step: {},
});
// 选择的行数据ids
const selectedIds = ref([] as string[] | number[] | any);
// 选择的行数据
const selected: any = ref({});
let dialog = reactive<any>({
	addOrUpdate: {
		// 打开状态
		open: false,
		// 标题
		title: '',
		// 表单数据
		form: {},
		// 按钮加载中状态
		btnLoading: false,
		// 表单校验规则
		rule: {
			name: [{ required: true, message: '业务名称不能为空', trigger: 'blur' }],
			// type: [{ required: true, message: '步骤设置必选', trigger: 'change' }],
			isKey: [{ required: true, message: '是否关键业务必选', trigger: 'change' }],
			sequence: [{ validator: validateShowOrder, trigger: 'blur' }],
		},
	},
	imp: {
		// ref
		ref: 'uploadRef',
		// 打开状态
		open: false,
		// 标题
		title: '导入',
		// 上传请求头
		headers: {
			Authorization: 'Bearer ' + getToken(),
		},
		// 最多导入数
		limit: 1,
	},
});

const state = reactive<any>({
	systemOptions: [],
	resourceCodes: [],
});

let tableRef = ref();
let isIndeterminate = ref(false);

/**
 * 全选
 */
function selectAllChange(val: any) {
	let flag = val.length > 0 ? true : false;
	setChecked(impTableData.data, flag);
}
/**
 * 递归选中
 * @param row 单行数据
 * @param flag 状态
 */
function setChecked(row: any, flag: any) {
	for (let item of row) {
		item.checked = flag;
		item.isIndeterminate = false;
		if (item.stepList && item.stepList.length > 0) {
			setChecked(item.stepList, flag);
		}
	}
}
/**
 * 把已选中的数据checked返回
 * 计算选中数据是否和数据长度一致
 */
function calcCheckedTotal(list: any) {
	let subCountChecked = list.map((item: any) => item.checked);
	// count：{true：xx, false: xx}，分别获取true状态有几个，false状态有几个
	let count = subCountChecked.reduce(function (accumulator: any, currentValue: any) {
		return accumulator[currentValue] ? ++accumulator[currentValue] : (accumulator[currentValue] = 1), accumulator;
	}, {});
	return {
		checkedArr: subCountChecked,
		isTrue: count.true === list.length,
		checkedTotal: count.true === undefined ? 0 : count.true,
	};
}
const myTableRef = ref();
/**
 * 复选框点击
 */
function handleCheck(row: any) {
	updateChildCheckedStatus(row);
	updateParentCheckedStatus(row);
	recuTableChecked();
}
/**
 * 表头全选框不是自定义的，所以设置表头全选框的状态,因固定只有两层，就不做递归处理
 */
function recuTableChecked() {
	const { checkedTotal } = calcCheckedTotal(impTableData.data);
	console.log(checkedTotal, 'checkedTotal');

	impTableData.data.forEach((item: any) => {
		// 选中和半选状态都将被表格获取到，并设置状态
		myTableRef.value.toggleRowSelection(item, item.checked || item.isIndeterminate);
		if (item.stepList !== null && item.stepList.length > 0) {
			item.stepList.forEach((child: any) => {
				/**
				 * 主要是处理当其他外层表格没有选中的情况下，选中某外层子数据，表格状态不会更新为半选中状态，
				 * 	如果有一个状态是false，并且表格获取到的外层数据选中长度大于0，就可以将外层取消表格状态，此时表格依旧是半选中状态
				 */
				if (!child.checked && checkedTotal > 0) {
					myTableRef.value.toggleRowSelection(item, false);
				}
			});
		}
	});
}
/**
 * 更新子节点状态
 */
function updateChildCheckedStatus(row: any) {
	if (!row.stepList) {
		const parent = findParent(row);
		if (parent) {
			parent.isIndeterminate = parent.isIndeterminate ? false : true;
		}
		if (row.stepList && row.stepList.length > 0) {
			row.stepList.forEach((child: any) => {
				child.checked = row.checked;
				updateChildCheckedStatus(child);
			});
		}
	} else {
		row.isIndeterminate = row.isIndeterminate ? false : true;
		if (row.stepList && row.stepList.length > 0) {
			row.stepList.forEach((child: any) => {
				child.checked = row.checked;
				updateChildCheckedStatus(child);
			});
		}
	}
}

/**
 * 更新父节点状态
 */
function updateParentCheckedStatus(row: any) {
	const parent = findParent(row);
	if (parent) {
		parent.checked = parent.stepList.every((child: any) => child.checked);
		if (parent.checked) {
			parent.isIndeterminate = false;
			return;
		}
		const { checkedArr, isTrue } = calcCheckedTotal(parent.stepList);
		if (checkedArr.includes(true) && !isTrue) {
			parent.isIndeterminate = true;
		} else {
			parent.isIndeterminate = false;
		}

		row.stepList && updateParentCheckedStatus(parent);
	} else {
		if (row.stepList === null) {
			return;
		}
		if (row.stepList.every((child: any) => child.checked)) {
			row.checked = true;
			row.isIndeterminate = false;
		} else {
			row.checked = false;
			row.isIndeterminate = false;
		}
	}
}
/**
 * 查找父级
 */
function findParent(row: any) {
	const getParent: any = (data: any, row: any) => {
		for (const item of data) {
			if (item.stepList && item.stepList.length > 0) {
				if (item.stepList.includes(row)) {
					return item;
				}
				const parent = getParent(item.stepList, row);
				if (parent) {
					return parent;
				}
			}
		}
		return null;
	};
	return getParent(impTableData.data, row);
}
/**
 * 查询系统选项
 */
function searchSystemFn(): void {
	system().then((res: ApiResponse | any) => {
		state.systemOptions = res.data;
		if (route.query.systemId) {
			searchFormData.systemId = route.query.systemId;
		} else {
			searchFormData.systemId = state.systemOptions[0].value;
		}
		handlerQuery();
	});
}

onMounted(() => {
	// if (route.query.systemCode) {
	// 	searchFormData.systemCode = route.query.systemCode;
	// }
	searchSystemFn();
});

function formInited() {
	if (!route.query.systemCode) {
		handlerQuery();
	}
}
/**
 * 校验关键业务顺序
 */
function validateShowOrder(rule: any, value: any, callback: any) {
	if (dialog.addOrUpdate.form.isKey == 1 && (!value || value == 0)) {
		callback(new Error('关键业务顺序不能为空或零'));
	} else {
		callback();
	}
}
/**
 * 关闭新增或修改弹出层
 */
function closeAddOrUpdateDialog() {
	dialog.addOrUpdate.open = false;
}

/**
 * 选择行数据
 */
function handlerSelectionChange(selects: any) {
	selectedIds.value = selects.map((item: any) => item.id);
	selected.value = selects;
}

function handlerQuery(filter?: any) {
	queryFilter();
	if (typeof filter === 'function' && !filter()) {
		return;
	}
	tableConfig.loading = true;
	querySynchronousBusiness(searchFormData)
		.then((res: ApiResponse | any) => {
			tableConfig.loading = false;
			if (res.code !== 0) {
				return;
			}
			if (res.data !== null) {
				tableData.data = res.data.records;
				tableConfig.pagination.total = res.data.total;
			}
		})
		.catch((e: any) => {
			tableConfig.loading = false;
		});
}
function selectionEffectAttr(selects: any) {
	currentEffectSelects.value = selects;
}
function queryFilter() {
	// 关闭标识属性下拉框
	proxy.$refs.customSelectRef.hideCustom();
	// 设置查询值
	searchFormData.isConfirm = null;
	searchFormData.isKey = null;
	const effectList = JSON.parse(JSON.stringify(currentEffectSelects.value));
	effectList.forEach((effect: any) => {
		if (effect.field === 'isConfirm') {
			searchFormData.isConfirm = effect.val;
		} else if (effect.field === 'isKey') {
			searchFormData.isKey = effect.val;
		}
	});
	return true;
}
/**
 * 判断是否能取消与确认
 */
function checkStatus(isConfirm: any) {
	let flag = false;
	if (selected.value !== undefined && selected.value !== null && selected.value.length > 0) {
		selected.value.forEach((item: any) => {
			if (item.isConfirm == isConfirm) {
				flag = true;
			}
		});
	}
	return flag;
}
/**
 * 改变是否关键业务
 */
function changeKeyBusiness(value: any) {
	if (value === 0) {
		dialog.addOrUpdate.form.showOrder = undefined;
		addDialogForm.showOrderDisabled = true;
	} else if (value === 1) {
		addDialogForm.showOrderDisabled = false;
	}
}
/**
 * 新增
 */
function handlerAdd() {
	// 判断窗口是否打开
	if (!dialog.addOrUpdate.open) {
		// 表单重置
		dialog.addOrUpdate.form = {};
		// 设置系统编码
		dialog.addOrUpdate.form.systemCode = searchFormData.systemCode;
		// proxy.resetForm('addOrUpdateForm');
		// 标题
		dialog.addOrUpdate.title = '新增';
		// 打开窗口
		dialog.addOrUpdate.open = true;
		return;
	}
	// 校验参数
	proxy.$refs['addOrUpdateForm'].validate((valid: boolean) => {
		if (!valid) {
			return;
		}
		// 调用接口
		dialog.addOrUpdate.btnLoading = true;
		dialog.addOrUpdate.form.systemId = searchFormData.systemId;
		addSynchronousBusiness(dialog.addOrUpdate.form).then((res) => {
			dialog.addOrUpdate.btnLoading = false;
			if (res.code !== 0) {
				proxy.$modal.msgError(res.msg);
				return;
			}
			// 关闭弹出层
			closeAddOrUpdateDialog();
			// 刷新列表
			searchFormData.pageNum = 1;
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('新增成功！');
		});
	});
}
/**
 * 确认
 */
function handlerConfirm() {
	proxy.$modal
		.confirm('是否确认所选项?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
		.then(() => {
			// 调用接口
			return confirmByIds(selected.value.map((item: any) => item.id));
		})
		.then(() => {
			// 刷新列表
			searchFormData.pageNum = 1;
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('确认成功！');
		})
		.catch(function () {});
}
/**
 * 删除
 */
function handlerDelete() {
	let dialogStr = '是否确认删除所选项?';
	for (let i = 0; i < selected.value.length; i++) {
		if (selected.value[i].stepCount > 0) {
			dialogStr = '所选业务下面有步骤，是否确认删除?';
			break;
		}
	}
	proxy.$modal
		.confirm(dialogStr, '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
		.then(() => {
			// 调用接口
			return deleteSynchronousBusinessByIds(selectedIds.value);
		})
		.then(() => {
			// 刷新列表 计算是否要查询上一页的数据
			if (tableData.total && searchFormData.pageSize) {
				// 删除后的总条数
				let totalCount = tableData.total - selectedIds.value.length;
				// 计算删除后的总页数
				let totalPage = Math.ceil(totalCount / searchFormData.pageSize);
				// 如果删除后的总页数小于1, 置为1
				totalPage = totalPage < 1 ? 1 : totalPage;
				// 判断删除前的页数是否大于删除后的总页数, 计算当前页应该是多少赋值给查询表单
				searchFormData.pageNum = searchFormData.pageNum > totalPage ? totalPage : searchFormData.pageNum;
			} else {
				searchFormData.pageNum = 1;
			}
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('删除成功！');
		});
}
/**
 * 修改
 */
function handlerEdit() {
	// 判断窗口是否打开
	if (!dialog.addOrUpdate.open) {
		// 数据回显，数据需要拷贝一下
		const d = JSON.parse(JSON.stringify(selected.value[0]));
		dialog.addOrUpdate.form = d;
		// 标题
		dialog.addOrUpdate.title = '修改';
		// 打开窗口
		dialog.addOrUpdate.open = true;
		if (d.isKey === 1) {
			addDialogForm.showOrderDisabled = false;
		} else {
			dialog.addOrUpdate.form.showOrder = undefined;
			addDialogForm.showOrderDisabled = true;
		}
		return;
	}

	// 校验参数
	proxy.$refs['addOrUpdateForm'].validate((valid: boolean) => {
		if (!valid) {
			return;
		}
		// 调用接口
		dialog.addOrUpdate.btnDisabled = true;
		editSynchronousBusiness(dialog.addOrUpdate.form).then((res) => {
			dialog.addOrUpdate.btnDisabled = false;
			if (res.code !== 0) {
				proxy.$modal.msgError(res.msg);
				return;
			}
			// 关闭弹出层
			closeAddOrUpdateDialog();
			// 刷新列表
			searchFormData.pageNum = 1;
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('修改成功！');
		});
	});
}
/**
 * 取消确认
 */
function handlerCancel() {
	proxy.$modal
		.confirm('是否将所选项改为未确认状态?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
		.then(() => {
			// 调用接口
			return cancelByIds(selected.value.map((item: any) => item.id));
		})
		.then(() => {
			// 刷新列表
			searchFormData.pageNum = 1;
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('取消确认成功！');
		})
		.catch(() => {});
}

function fileChange(file: any) {
	fileList.value[0] = file.raw;
}
function handlerRemove() {
	fileList.value = [];
}
function handlerSuccess() {
	proxy.$modal.msgSuccess('上传成功，点击确认导入!');
}
function handlerError() {
	proxy.$modal.msgError('上传失败');
}
/**
 * 导入
 */
function handlerImport() {
	importFlag.value = true;
	// 判断窗口是否打开
	if (!dialog.imp.open) {
		impSearchFormData.name = undefined;
		record.business = {};
		record.step = {};
		selectedImpStepCodes.value = [];
		impSearchFormData.systemCode = searchFormData.systemCode;
		dialog.imp.title = '导入';
		handlerImpQuery();
		dialog.imp.open = true;
		return;
	}

	state.resourceCodes = [];
	impTableData.data.forEach((item: any) => {
		if (item.stepList && item.stepList.length > 0) {
			item.stepList.forEach((items: any) => {
				if (items.checked) {
					state.resourceCodes.push(items.stepCode);
				}
			});
		}
	});
	if (state.resourceCodes === null || state.resourceCodes.length == 0) {
		proxy.$modal.msgError('未选择步骤，请先选择步骤');
		return;
	}
	if (fileList.value[0]) {
		let form = new FormData();
		const isLt5M = fileList.value[0].size / 1024 / 1024 < 5;
		if (!isLt5M) {
			proxy.$modal.msgError('文件大小不能超过5M');
		} else {
			form.append('file', fileList.value[0]);
			form.append('resourceCodes', state.resourceCodes.join(','));
			batchImport(form).then((rs: ApiResponse | any) => {
				if (rs.code === 0) {
					proxy.$modal.msgSuccess(rs.data);
					dialog.imp.open = false;
					handlerQuery();
				} else {
					proxy.$modal.msgError(rs.msg);
				}
			});
		}
	} else {
		proxy.$modal.msgError('请先上传文件');
	}
}
// 下载导入模板
function downloadTemplate() {
	importTemplate().then((res) => {
		downloadFromBlob(res, '专属指标导入模板').then((o) => {
			if (!o.flag) {
				proxy.$modal.msgWarning(o.msg);
			}
		});
	});
}
// 查询业务-步骤
function handlerImpQuery() {
	impTableConfig.loading = true;
	impSearchFormData.systemId = searchFormData.systemId;
	queryToImport(impSearchFormData).then((res: any) => {
		impTableConfig.loading = false;
		if (res.code !== 0) {
			return;
		}
		if (res.data !== null) {
			impTableData.data = res.data.records.map((item: any) => {
				return { isIndeterminate: false, checked: false, ...item };
			});
			impTableConfig.pagination.total = res.data.total;
		}
	});
}
function hanlerSearchStepDataFn(businessCode: string) {
	let obj = {
		businessCode,
	};
	query(obj).then((res: ApiResponse | any) => {
		impStepTableData.data = res.data.records;
	});
}
// 点击业务
function handlerRowClick(row: any) {
	console.log(row, 'row');
	// let businessCode = row.businessCode;
	state.resourceCodes = row;
	// hanlerSearchStepDataFn(businessCode);
}
// 表单提交
function handlerSubmit() {
	if (dialog.addOrUpdate.title === '新增') {
		handlerAdd();
	} else {
		handlerEdit();
	}
}
// 关闭导入导出页面
function closeImpDialog() {
	impStepTableData.data = [];
	dialog.imp.open = false;
}
// 导出
function handlerExport() {
	importFlag.value = false;
	// 判断窗口是否打开
	if (!dialog.imp.open) {
		record.business = {};
		record.step = {};
		impSearchFormData.name = undefined;
		selectedImpStepCodes.value = [];
		impSearchFormData.systemCode = searchFormData.systemCode;
		dialog.imp.title = '导出';
		handlerImpQuery();
		dialog.imp.open = true;
		return;
	}
	// if (selectedImpStepCodes.value === null || selectedImpStepCodes.value.length == 0) {
	// 	proxy.$modal.msgError('未选择步骤，请先选择步骤');
	// 	return;
	// }
	// impTableData.data

	state.resourceCodes = [];
	impTableData.data.forEach((item: any) => {
		if (item.stepList && item.stepList.length > 0) {
			item.stepList.forEach((items: any) => {
				if (items.checked) {
					state.resourceCodes.push(items.stepCode);
				}
			});
		}
	});
	if (state.resourceCodes.length === 0) {
		proxy.$modal.msgError('未选择步骤，请先选择步骤');
		return;
	}
	download(state).then((res) => {
		downloadFromBlob(res, '专属指标列表').then((o: ApiResponse | any) => {
			if (!o.flag) {
				proxy.$modal.msgWarning(o.msg);
			} else {
				dialog.imp.open = false;
			}
		});
	});
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.effect-attr-selects {
	display: inline-block;
	margin: 2px 10px;
	padding: 0 5px;
	border: 1px solid #dcdfe6;
	border-radius: 4px;
}
.el-form-item,
.el-select,
.custom-select-container {
	width: 100%;
}
</style>
